<template>
  <a-modal
    v-model:visible="visible"
    :title="modalTitle"
    wrapClassName="custom-modal custom-modal__big min-base-modal modal-280"
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
    :width="modalWidth"
  >
    <!-- height="41.25rem" -->
    <div v-if="modalType === 'delete'" class="red-prompt flex flex-col mb-6">
      <div>确认删除角色{{ formState.roleName }}吗?</div>
    </div>
    <div v-else class="p-4">
      <a-form
        ref="formRef"
        :model="formState"
        name="platform-config"
        layout="vertical"
      >
        <a-row :gutter="24" style="width: 100%" class="title first-title">
          <div class="title-icon"></div>
          基本信息</a-row
        >
        <a-row :gutter="24" style="width: 100%">
          <a-col :span="12">
            <a-form-item label="角色名称" name="roleName" required>
              <a-input
                v-model:value.trim="formState.roleName"
                placeholder="请输入角色名称"
                maxLength="20"
                :disabled="isAdmin"
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="2"></a-col> -->
          <a-col :span="12"
            ><a-form-item
              label="备注"
              :label-col="{ style: { width: '6rem' } }"
              name="remark"
            >
              <a-input
                v-model:value="formState.remark"
                placeholder="请输入备注"
                maxLength="100"
                :disabled="isAdmin"
              /> </a-form-item
          ></a-col>
        </a-row>
        <!-- <a-row :gutter="24" style="width: 100%" class="title">
          <div class="title-icon"></div>
          数据权限</a-row
        > -->
        <!-- <a-row :gutter="24" style="width: 100%">
          <a-col :span="12"
            ><a-form-item label="数据级别" name="dataScope" required>
              <a-select
                :disabled="isAdmin"
                v-model:value="formState.dataScope"
                placeholder="请选择数据级别"
                :options="[
                  { value: 1, label: '全部' },
                  { value: 4, label: '本级机构及以下' }
                ]"
              /> </a-form-item
          ></a-col>
        </a-row> -->
        <a-row :gutter="24" style="width: 100%" class="title">
          <div class="title-icon"></div>
          功能权限</a-row
        >
        <a-row :gutter="24" style="width: 100%">
          <a-tree
            :key="curIndex"
            v-if="currentList.length"
            class="w-full role-tree"
            :fieldNames="replaceFields"
            checkable
            @check="checkData"
            v-model:checkedKeys="checkedKeys"
            :defaultExpandAll="true"
            :checkStrictly="true"
            :selectable="false"
            :tree-data="currentList"
            :disabled="isAdmin"
          >
          </a-tree>

          <!-- <a-tree
            v-if="currentList.length"
            :key="curIndex"
            checkable
            :fieldNames="replaceFields"
            v-model:checkedKeys="checkedKeys"
            :tree-data="currentList"
            :disabled="isAdmin"
            :selectable="false"
            :defaultExpandAll="true"
            class="w-full role-tree"
          /> -->
        </a-row>
      </a-form>
    </div>
    <template #footer>
      <a-button class="cancel" @click="handleCancel">取消</a-button>
      <a-button
        v-if="!isAdmin"
        key="submit"
        type="primary"
        :loading="loading"
        @click="handleOk"
      >
        {{
          modalType === 'delete' || modalType === 'forbidden' ? '确认' : '保存'
        }}
      </a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { editRole, addRole, removeRole } from '@/api/role'
import { computed, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import type { Menu, Role } from '@/api/model/role'
const loading = ref<boolean>(false)
const visible = ref<boolean>(false)
const formRef = ref()
const emit = defineEmits(['isOk', 'changeStatus'])

const props = defineProps({
  organizationList: {
    type: Array,
    default: () => []
  },
  roleList: {
    type: Array,
    default: () => []
  },
  modalType: {
    type: String,
    default: 'delete'
  },
  menuList: {
    type: Array<Menu>,
    default: () => []
  },
  isAdmin: {
    type: Boolean,
    default: false
  }
})

const roleType = ref<boolean>(true)
const curIndex = ref(0)
const replaceFields = {
  title: 'label',
  key: 'id'
}
// const menuIds = ref<number[]>([])
const modalTitle = computed(() => {
  if (props.modalType === 'delete') {
    return '删除'
  } else if (props.modalType === 'add') {
    return '添加角色'
  } else if (props.modalType === 'edit') {
    return '修改角色'
  } else {
    return '禁用用户'
  }
})

const modalWidth = computed(() => {
  if (props.modalType === 'delete') {
    return '23.75rem'
  } else if (props.modalType === 'add') {
    return '50.75rem'
  } else {
    return '50.75rem'
  }
})

const currentList = computed(() => {
  // return props.menuList.filter((item: any) => item.label !== '样本集预览')
  return props.menuList
})

const checkedKeys = ref<number[]>([])

const handleOk = async () => {
  const { modalType } = props
  try {
    if (modalType === 'delete') {
      await deleteUserFun()
      return
    }
    await formRef.value.validateFields()
    if (modalType === 'add') {
      await addRoleFun()
    } else if (modalType === 'edit') {
      await editRoleFun()
    }
  } catch (errorInfo) {
    console.log('Failed:', errorInfo)
  }
}

// 删除用户
const deleteUserFun = async () => {
  loading.value = true
  removeRole(formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('删除成功！')
      emit('isOk')
    })
    .catch(() => {
      //   message.error('删除失败！')
      loading.value = false
      visible.value = false
    })
}

const handleCancel = () => {
  visible.value = false
}

const formState = reactive<Role>({
  roleId: undefined,
  roleName: '',
  remark: '',
  menuIds: [],
  dataScope: 1
})

const addRoleFun = () => {
  // formState.menuIds = [...checkedKeys.value, 21]
  formState.menuIds = checkedKeys.value
  if (checkedKeys.value.length === 0)
    return message.error('请至少选择一个菜单！')
  loading.value = true
  formState.roleId = undefined
  addRole(formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('新增角色成功！')
      emit('isOk')
    })
    .catch(() => {
      loading.value = false
      //   visible.value = false
      //   message.error('新增角色失败！')
    })
}

const editRoleFun = () => {
  // formState.menuIds = [...checkedKeys.value, 21]
  formState.menuIds = checkedKeys.value
  if (checkedKeys.value.length === 0)
    return message.error('请至少选择一个菜单！')
  loading.value = true
  editRole(formState)
    .then((res) => {
      loading.value = false
      visible.value = false
      message.success('修改成功！')
      emit('isOk')
    })
    .catch(() => {
      //   message.error('修改失败！')
      loading.value = false
      visible.value = false
    })
}

const showModal = (data?: Role) => {
  visible.value = true
  roleType.value = true
  curIndex.value = 0
  if (data) {
    formState.roleName = data.roleName
    formState.remark = data.remark
    formState.roleId = data.roleId
    formState.dataScope = 1
    checkedKeys.value = data.menuIds ?? []
    console.log(checkedKeys.value)
  } else {
    formState.roleName = ''
    formState.remark = ''
    formState.dataScope = 1
    checkedKeys.value = []
  }
}

const checkData = (keys: { checked: number[] }, e: any) => {
  const { node, checked } = e
  if (checked) {
    bindSelectChild(keys.checked, node)
    checkedKeys.value = bindSelect(keys.checked, node)
  } else {
    checkedKeys.value = bindUnselect(keys.checked, node)
  }
}

const bindSelect = (keys: number[], e: any) => {
  if (e.parent) {
    if (keys.indexOf(e.parent.key) < 0) keys.push(e.parent.key)
    if (e.parent.parent) bindSelect(keys, e.parent)
  }
  return keys
}
const bindSelectChild = (keys: number[], e: any) => {
  if (e.children) {
    e.children.forEach((i: any) => {
      if (keys.indexOf(i.id) < 0) keys.push(i.id)
      if (i.children) bindSelectChild(keys, i)
    })
  }
  return keys
}

const bindUnselect = (keys: number[], e: any) => {
  if (e.children) {
    e.children.forEach((i: any) => {
      if (keys.indexOf(i.id) > -1) {
        const index = keys.indexOf(i.id)
        keys.splice(index, 1)
        if (i.children) bindUnselect(keys, i)
      }
    })
  }
  return keys
}
defineExpose({ showModal })
</script>

<!-- <style lang="less">
.role-info {
  .unselected {
    color: #0d527d;
  }
}

.menu-list {
  font-size: 1rem;
  color: #8a8f99;

  .menu-chosen {
    color: @primary-text-color;
  }
}

.is-leaf {
  display: inline-flex !important;
  margin-right: 8px; /* 可以添加一些间距 */
}
</style> -->
<style lang="less" scoped>
/* stylelint-disable-next-line string-quotes */
@import './modal.less';
</style>
